<template>
  <main class="main-container">
    <div style="text-align: right">
      <el-upload
        ref="addUploader"
        :action="`${baseUrl}/upload`"
        :show-file-list="false"
        limit="1"
        :onSuccess="createBanner"
      >
        <el-button type="primary" size="large">新增轮播图</el-button>
      </el-upload>
    </div>
    <el-table :data="bannerList">
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="pic" label="图片">
        <template #default="{ row }">
          <img :src="fileUrl + row.pic" alt="图片" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div style="display: flex; align-items: center">
            <el-upload
              :ref="
                (e) => {
                  uploaderRefs.push(e);
                  return `uploader${row.id}`;
                }
              "
              :action="`${baseUrl}/upload`"
              :show-file-list="false"
              limit="1"
              :onSuccess="handleSuccess.bind(null, row)"
            >
              <el-button type="primary" link>替换</el-button>
            </el-upload>
            <el-button
              type="danger"
              style="margin-left: 20px"
              link
              @click="del(row.id)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
  </main>
</template>
<script setup lang="ts">
import { ref } from "vue";
import {
  getBanners,
  deleteBanner,
  updateBanner,
  addBanner,
} from "@/api/banner";
import { ElMessage } from "element-plus";
const fileUrl = window.config.fileUrl;
const baseUrl = window.config.baseUrl;
const addUploader = ref<any>(null);
const uploaderRefs = ref<any[]>([]);
let bannerList = ref<
  {
    id: number;
    pic: string;
  }[]
>([]);
const del = async (id: number) => {
  await deleteBanner(id);
  ElMessage.success("删除成功");
  getData();
};
const createBanner = async (res: any) => {
  await addBanner(res.filename);
  ElMessage.success("上传成功");
  addUploader.value.clearFiles();
  getData();
};
const handleSuccess = async (row: any, res: any) => {
  await updateBanner(row.id, res.filename);
  ElMessage.success("上传成功");
  uploaderRefs.value.forEach((ref) => {
    ref.clearFiles();
  });

  getData();
};
const getData = async () => {
  let data = await getBanners();
  bannerList.value = data.data;
};
getData();
</script>
<style scoped lang="less"></style>
